package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import dto.ShoppingItem;
import pojo.Food;
import pojo.User;
import service.UserManager;
import service.factory.UserManagerFactory;

 
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private UserManager manager;
   
    public LoginServlet() {
        super();
        manager = UserManagerFactory.getInstance();
    
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String psd = request.getParameter("password");
		
		User user = manager.loadUserByName(name);
 
		if(user != null){
			if(user.getPassword().trim().equals(psd.trim())){
				System.out.println("用户 "+name+" 登录成功");
				Logger.getLogger(LoginServlet.class).info("用户 "+name+" 登录成功");
				
			 
				Map<String , ShoppingItem> shoppingcart = new HashMap<String , ShoppingItem>();
				request.getSession().setAttribute("shoppingcart", shoppingcart);
				
				
				request.getSession().setAttribute("user", user);
				request.getRequestDispatcher("storelist.html").forward(request, response);
			} else {
				request.setAttribute("name", name);
				request.setAttribute("info", "密码错误");
				request.getRequestDispatcher("login.jsp").forward(request, response);
			 
			}
		}else{
             request.setAttribute("name", name);
			 request.getRequestDispatcher("regist.jsp").forward(request, response);
          
		} 
	}

}
